package com.woniuxy.permission.service.impl;

import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.client.MerchantClient;
import com.woniu.dto.SelectAllDto;
import com.woniu.dto.SiteDto;
import com.woniu.form.*;
import com.woniu.zsd.commons.core.exception.ZsdException;
import com.woniu.zsd.commons.core.model.Result;
import com.woniuxy.permission.entity.Permission;
import com.woniuxy.permission.mapper.PermissionMapper;
import com.woniuxy.permission.service.IPermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.permission.utils.MD5Util;
import com.woniuxy.permission.utils.OSSUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <p>
 * 管理原详情表 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-05-13
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements IPermissionService {

    @Resource
    private PermissionMapper permissionMapper;
    @Resource
    private OSSUtil ossUtil;
    @Resource
    private MerchantClient merchantClient;
    @Override
    public Permission login(LoginForm lf) throws Exception {

        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("user_name", lf.getUsername());
        Permission permission = permissionMapper.selectOne(queryWrapper);
        System.out.println("permission:"+permission);
        if (permission==null||permission.getDelet()!=0)throw new ZsdException("用户名错误",500);
        String password = MD5Util.md5(lf.getPassword(), lf.getUsername());
        if (!permission.getPassword().equals(password))throw new ZsdException("密码错误", 500);
        return permission;
    }

    @Override
    public void insertAdminInfo(AdminInfoForm aif)throws Exception {
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", aif.getUsername());
        Permission permission = permissionMapper.selectOne(queryWrapper);

        if(permission!=null)throw new ZsdException("用户名已存在", 500);
        // 查询是否存在相同手机号
        QueryWrapper<Permission> phoneWrapper = new QueryWrapper<>();
        phoneWrapper.eq("phone", aif.getPhone());
        Permission phoneExist = permissionMapper.selectOne(phoneWrapper);

        // 判断手机号是否已存在
        if (phoneExist != null) {
            throw new ZsdException("手机号已存在", 500);
        }

        Permission permission1 = new Permission();
        permission1.setName(aif.getName());
        permission1.setPhone(aif.getPhone());
       permission1.setHeadImg("https://theshy111.oss-cn-chengdu.aliyuncs.com/f4cc478e-d711-402d-afa8-ccca6b801788.PNG");
        permission1.setState(2);
        permission1.setRoleId(aif.getRole());
        permission1.setSiteId(aif.getSiteId());
        permission1.setUserName(aif.getUsername());
        permission1.setPassword(MD5Util.md5("123123", aif.getUsername()));
        permission1.setDelet(0);
        permissionMapper.insert(permission1);

    }

    @Override
    public boolean checkDuplicateInfo(Integer adminId, String username, String phone) {
        // 查询数据库中是否存在相同的账号或手机号，排除当前管理员
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",  adminId)
                .and(wrapper -> wrapper.eq("username", username).or().eq("phone", phone));
        return this.count(queryWrapper) > 0;
    }

    @Override
    public void updateAdminInfo(UpdateAdminInfoForm uaif) {
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", uaif.getAdminId());
        if (queryWrapper==null)throw new ZsdException("不存在该用户", 500);
        Permission permission = new Permission();
        permission.setName(uaif.getName());
        permission.setPhone(uaif.getPhone());
        permission.setState(uaif.getState());
        permission.setRoleId(uaif.getRole());
        permission.setSiteId(uaif.getSiteId());
        permission.setUserName(uaif.getUsername());
        permissionMapper.update(permission, queryWrapper);

    }

    @Override
    public void deleteAdminInfoById(Integer adminId) {
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", adminId);
        if (permissionMapper.selectOne(queryWrapper) == null)throw new ZsdException("不存在该用户", 500);
        Permission permission = new Permission();
        permission.setDelet(1);
        permissionMapper.updateById(permission);
    }

    @Override
    public IPage<SelectAllDto> selAll( SelectAllForm selectAllForm) {

        Page<SelectAllDto> page = new Page<>(selectAllForm.getPageNum(), selectAllForm.getPageSize());
        IPage<SelectAllDto> iPage = permissionMapper.selectWithRoleName(page, selectAllForm);
        System.out.println("iPage:"+iPage);
        List<SelectAllDto> records = iPage.getRecords();
        for (SelectAllDto record : records){

            Integer siteId = record.getSiteId();
            if (siteId!=null) {
                try {
                    Result<SiteDto> result = merchantClient.siteId(siteId);
                    if (result != null && result.getData() != null) {
                        record.setSiteName(result.getData().getSiteName());
                    } else {
                        record.setSiteName("未知站点");
                    }
                } catch (Exception e) {
                    record.setSiteName("未知站点");
                }
            }else {
                record.setSiteName("未设置站点");
            }
        }

        return iPage;


    }


    @Override
    public boolean updatePassword(Integer adminId, UpdatePasswordForm updatePasswordForm) throws Exception {
        Permission admin = permissionMapper.selectById(adminId);
        if (admin==null)throw new ZsdException("用户不存在", 500);
        String oldPwd = MD5Util.md5(updatePasswordForm.getOldPassword(), admin.getUserName());
        System.out.println("旧密码"+oldPwd);
        String newPwd = MD5Util.md5(updatePasswordForm.getNewPassword(), admin.getUserName());
        //验证旧密码是否正确
        if (!oldPwd.equals(admin.getPassword()))throw new ZsdException("旧密码错误", 500);
        admin.setPassword(newPwd);
        permissionMapper.updateById(admin);
        return true;
    }



    @Override
    public Permission getFindById(Integer adminId) {
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", adminId);
        Permission permission = permissionMapper.selectOne(queryWrapper);
        if (permission==null)throw new RuntimeException("没有此用户");
        if (permission.getDelet()==1)throw new RuntimeException("此用户已被删除");
        return permission;
    }

    @Override
    public Integer getCustomerService() {
        List<Permission> adminInfos = permissionMapper.selectList(new QueryWrapper<Permission>().eq("role_id", 4));
        //从 adminInfos 随机一个角色为 4 的管理员
        int index = 0;
        if (adminInfos.size() > 0) {
            Random random = new Random();
            index = random.nextInt(adminInfos.size());
            return adminInfos.get(index).getId();
        }
        return index;
    }
}
